package priv.stones.multi_thread.runnable;

/**
 * @Author: Stones
 * @Description:生产者与消费者模型
 * @Date: 2017/9/21 15:06
 */
public class ProducerWithConsumerModel1 {

    public static void main(String[] args) {
        Storage storage = new Storage();
        Producer producer = new Producer(storage);
        Consumer consumer = new Consumer(storage);
        new Thread(producer, "producer").start();
        new Thread(consumer, "consumer").start();
    }

}

/**
 * 仓库
 */
class Storage {
    private String product;
    private boolean mark = false;

    public synchronized void getProduct() throws InterruptedException {
        if (!mark) {
            this.wait();
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "   消费了   " + product);
        mark = false;
        this.notify();
    }

    public synchronized void setProduct(String product) throws InterruptedException {
        if (mark) {
            this.wait();
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.product = product;
        System.out.println(Thread.currentThread().getName() + "   生产了   " + product);
        mark = true;
        this.notify();
    }
}

/**
 * 生产者
 */
class Producer implements Runnable {
    private Storage storage;

    public Producer(Storage storage) {
        this.storage = storage;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                storage.setProduct("product" + i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

/**
 * 消费者
 */
class Consumer implements Runnable {

    private Storage storage;

    public Consumer(Storage storage) {
        this.storage = storage;
    }


    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                storage.getProduct();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}


